'use strict';

const Controller = require('egg').Controller;
const jwt = require('jsonwebtoken')

class HomeController extends Controller {
    async login() {
        const { ctx, app } = this;
        const { username, password } = ctx.request.body
        let data = await app.mysql.get('login', { username, password })
        if (data) {
            const token = jwt.sign(data.username, '1901B')
            ctx.body = {
                code: '000',
                msg: '成功',
                token,
                data
            }
        } else {
            ctx.body = {
                code: '001',
                msg: "失败",
            }
        }
    }

    async register() {
        const { ctx, app } = this;
        const { username, password } = ctx.request.body
        let data = await app.mysql.get('login', { username })
        if (data) {
            ctx.body = {
                code: '002',
                msg: "账号已被注册"
            }
        } else {
            await app.mysql.insert('login', { username, password })
            ctx.body = {
                code: '003',
                msg: "账号注册成功",
                data
            }
        }
    }
}

module.exports = HomeController;
